﻿
namespace SeedObject
{
    /// <summary>
    /// http module to restore the occupied seeds in a request
    /// </summary>
    public sealed class Restorer : System.Web.IHttpModule
    {
        private System.Web.HttpApplication Context;
        /// <summary>
        /// Start module
        /// </summary>
        /// <param name="Context"></param>
        void System.Web.IHttpModule.Init(System.Web.HttpApplication context)
        {
            this.Context = context;

            //set the restorer in PostRequestHandlerExecute event
            context.PostRequestHandlerExecute += Do;
        }
        private void Do(object sender, System.EventArgs e)
        {
            // if not page
            if (!(Context.Context.Handler is System.Web.UI.Page))
                return;

            string Key = Context.Context.Handler.GetHashCode().ToString(Utility.CultureInfo);
            // routed to the collection of seeds to restore
            System.Collections.Generic.IList<ISeed> Seeds
                = Context.Session[Key] as System.Collections.Generic.IList<ISeed>;
            if (Seeds != null)
            {
                // iterate over the objects used and restore
                foreach (ISeed Seed in Seeds)
                    // restored if busy
                    if (Seed.InA(State.Busy))
                        Seed.Restore();
                // eliminates what used in the handler 
                Seeds.Clear();
            }
        }
        /// <summary>
        /// destructor module
        /// </summary>
        void System.Web.IHttpModule.Dispose() 
        { 
        }

    }
}
